import VueRouter from "vue-router";
import Vue from "vue";

// 1、注册组件
Vue.use(VueRouter);

// 2、创建路由规则
const routes = [
    {
        path: "/",
        redirect: '/login'
    },
    {
        path: "/login",
        component: ()=>import("@/views/login.vue")
    },
    {
        path: "/index",
        component: ()=>import("@/views/index.vue"),
        redirect: "/index/home",
        children: [
            { // 注册二级路由
                path: "home",
                component: ()=>import("@/views/home.vue")
            },
            {
                path: "articleList",
                component:()=>import("@/views/articleList.vue")
            },
            {
                path: "articleAdd",
                component:()=>import("@/views/articleAdd.vue")
            }
        ]
    }
]

// 3、生成路由对象
const router = new VueRouter({
    routes
})

// 导航守卫  所有页面必须登录后才能让用户访问（路由权限）
// 除了登录页面其他所有页面 都必须登录后才能访问
router.beforeEach((to,from,next)=>{
    let token = localStorage.getItem("72-backend-token")
    if(to.path!="/login"&&!token){
        next("/login")
    }else{
        next()
    }
})

// 重新下载路由也能解决这个问题
// 解决重复跳转到同一个路由地址报错问题
// 解决跳转页面之前进行重定向报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

// 4、导出路由对象
export default router